package com.bite.common.message.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class SMSSender {

    @Value("${sms.spug.patternId}")
    private String patternId;

    @Resource(name = "dateTimeFormatter")
    private DateTimeFormatter dateTimeFormatter;

    @Value("${sms.spug.baseUrl}")
    private String baseUrl;

    public boolean sendWechat(String code, String phone ,Long ttl) {

        String url = String.format(baseUrl, patternId);
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("ttl", ttl);
        params.put("phone", phone);
        params.put("now", LocalDateTime.now().format(dateTimeFormatter));
        try {
            String result = SendUtils.sendPostRequest(url, params);
            JSONObject jsonObject = JSON.parseObject(result);
            if (!"200".equals(jsonObject.get("code").toString())) {
                log.error("[sendWechat] 出现异常 result：${}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("[sendWechat] 出现异常 e：${}", e.toString());
            return false;
        }
        return true;
    }
}
